package top.zhdev.community.controller;

import org.apache.kafka.common.network.Mode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import top.zhdev.community.entity.DiscussPost;
import top.zhdev.community.entity.Page;
import top.zhdev.community.service.ElasticsearchService;
import top.zhdev.community.service.LikeService;
import top.zhdev.community.service.UserService;
import top.zhdev.community.utils.CommunityConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 搜索处理器 使用elasticsearch 做处理
 */

@Controller
public class SearchController implements CommunityConstant {

    private ElasticsearchService searchService;
    private UserService userService;
    private LikeService likeService;

    @Autowired
    public void setSearchService(ElasticsearchService searchService) {
        this.searchService = searchService;
    }

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setLikeService(LikeService likeService) {
        this.likeService = likeService;
    }

    /**
     * 搜索功能
     * @param keyword
     * @param page
     * @param model
     * @return
     */
    @GetMapping("/search")
    public String search(String keyword, Page page, Model model){
        // 搜索帖子
        org.springframework.data.domain.Page<DiscussPost> searchResults = searchService.searchDiscussPost(keyword,page.getCurrent() - 1,page.getLimit());

        // 聚合数据
        List<Map<String,Object>> discussPosts = new ArrayList<>();
        if(searchResults != null){
            for (DiscussPost post : searchResults){
                Map<String,Object> map = new HashMap<>();

                // 帖子
                map.put("post",post);
                // 作者
                map.put("user",userService.getUserById(post.getUserId()));
                // 点赞数量
                map.put("likeCount",likeService.getUserLikeCount(post.getUserId()));

                discussPosts.add(map);
            }
        }

        model.addAttribute("discussPosts",discussPosts);
        model.addAttribute("keyword",keyword);

        page.setPath("search?keyword=" + keyword);
        page.setRows(searchResults == null ? 0 : (int) searchResults.getTotalElements());
        return "/site/search";
    }
}
